const puppeteer = require('puppeteer');
const fs = require('fs');
const dayjs = require('dayjs');
const { createEvents } = require("ics");
const path = require('path');
const { v4: uuidv4 } = require("uuid");

// browser参数为必传
async function renderTimetableToImage(data, browser) {
  if (!browser) throw new Error('Puppeteer browser instance is not available');
  
  function renderHtmlTemplate(templateName, data, isTest = false) {
    const templatePath = path.join(__dirname, 'public', `${templateName}.html`);
    let html = fs.readFileSync(templatePath, 'utf-8');
    if(isTest){
      return html;
    }
    Object.keys(data).forEach(key => {
      html = html.replace(new RegExp(`{{${key}}}`, 'g'), data[key]);
    });
    return html;
  }
  const html = renderHtmlTemplate('template01', {
    shop_name: data.shop_name,
    plan_date: data.plan_date,
    mini_qrcode: data.mini_qrcode,
    header_bg_image: transformHeaderBgHtml(data.header_bg_image),
    tips: transformTipsHtml(data.tips),
    courses: transformCourseHtml(data.courses)
  });
  const page = await browser.newPage();
  await page.setViewport({ width: 750, height: 600 }); // 固定宽度为750，高度随便填
  await page.setContent(html, { waitUntil: 'networkidle0' });
  const screenshotBuffer = await page.screenshot({ fullPage: true });
  await page.close();
  return screenshotBuffer;
}
// 模版转换方法
// 转换Tips
function transformTipsHtml(tips = ''){
  if(tips){
    return `<div class="tips-box">Tips：${tips}</div>`
  }
  return ''
}
// 转换HeaderBgImage
function transformHeaderBgHtml (header_bg_image = '') {
  if(header_bg_image){
    return `background-image: linear-gradient(to right, rgba(233,32,40,0.75) 60%, rgba(242,136,139,0.6) 100%),
                url('${header_bg_image}');`
  }
  return `background-image: linear-gradient(to right, rgba(233,32,40,0.75) 60%, rgba(242,136,139,0.6) 100%);`
}
// 转换课程渲染
function transformCourseHtml (courses = '') {
  if(courses){
      const newData = transformCourseToData(courses);
      function transformOneDay (list) {
        if(list && list.length > 0){
          let html = '';
         
          list.forEach((item) => {
            let course_text = '';
            if(Number(item.type) === 1){
              course_text = 'appointment'
            }
            if(Number(item.type) === 2){
              course_text = 'private'
            }
            if(Number(item.type) === 3){
              course_text = 'plan'
            }
            html += ` <div class="course-card ${course_text}">
                <div class="course-name">${item.name}</div>
                <div class="course-info">
                    <img class="avatar" src="${item.teacher_info.avatar}" alt="avatar">
                    <div>
                        <div class="teacher">${item.teacher_name}</div>
                        <div class="time">${item.time_duration_text}</div>
                    </div>
                </div>
            </div>`
          })
          return `<div class="cell">
              ${html}
          </div>`
        }
        return `<div class="cell empty">暂无课程</div>`
      }
      let html = '';
      newData.forEach((item) => {
        html += ` <div class="cell-box">
            <div class="weekday">${item.week}</div>
            ${transformOneDay(item.mooring)}
            ${transformOneDay(item.afternoon)}
          </div>`
      })
      return html;
  }
  return ''
}
/**
 * 课程数据转换 方便渲染
 * params coursesJson [{"time_duration_text": "12:00", "start_time": 176123123}],
 * @return [{week: "周一", afternoon: [{"time_duration_text": "12:00", "start_time": 176123123}], mooring: [{"time_duration_text": "12:00", "start_time": 176123123}]},]
 * */ 
function transformCourseToData(coursesJson){
  let courses = [];
  if(coursesJson){
    if (typeof coursesJson === 'string') {
      courses = JSON.parse(coursesJson)
    } else {
      courses = coursesJson
    }
  }
  // 初始化周一到周日
  const weekDays = [
    { week: '周一', mooring: [], afternoon: [] },
    { week: '周二', mooring: [], afternoon: [] },
    { week: '周三', mooring: [], afternoon: [] },
    { week: '周四', mooring: [], afternoon: [] },
    { week: '周五', mooring: [], afternoon: [] },
    { week: '周六', mooring: [], afternoon: [] },
    { week: '周日', mooring: [], afternoon: [] },
  ];

  courses.forEach(course => {
    const d = dayjs(course.start_time * 1000); // 假设start_time是秒级时间戳
    const weekIndex = d.day() === 0 ? 6 : d.day() - 1; // dayjs: 0=周日, 1=周一...
    const hour = d.hour();
    if (hour < 12) {
      weekDays[weekIndex].mooring.push(course);
    } else {
      weekDays[weekIndex].afternoon.push(course);
    }
  });
  return weekDays;
}
//课程数据转换 方便订阅服务
function transformCourseToSubscribe(coursesJson, baseUrl){
   let courses = [];
  if(coursesJson){
    if (typeof coursesJson === 'string') {
      courses = JSON.parse(coursesJson)
    } else {
      courses = coursesJson
    }
  }
  const COURSE_TYPE_LABELS = {
    1: "预约课程",
    2: "私教课",
    3: "常规课",
  };

  const events = courses.map((course) => {
    const start = dayjs.unix(course.start_time);
    const durationMins = course.duration || 60;
    const hours = Math.floor(durationMins / 60);
    const minutes = durationMins % 60;

    return {
      start: [
        start.year(),
        start.month() + 1,
        start.date(),
        start.hour(),
        start.minute(),
      ],
      duration: { hours, minutes },
      title: `${course.name}（${COURSE_TYPE_LABELS[course.type] || "课程"}）`,
      description: `老师：${course.teacher_name}`,
      location: "舞蹈教室",
      status: "CONFIRMED",
      busyStatus: "BUSY",
      alarms: [
        {
          action: "display",
          description: "课程开始提醒",
          trigger: { minutes: 30, before: true },
        },
      ],
    };
  });

  return new Promise((resolve, reject) => {
    createEvents(events, (error, value) => {
      if (error) return reject(error);

      const dirPath = path.join(__dirname, "public", "ics");
      if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath, { recursive: true });
      }

      const filename = `${uuidv4()}.ics`;
      const filePath = path.join(dirPath, filename);
      fs.writeFile(filePath, value, (err) => {
        if (err) return reject(err);

        const downloadUrl = `${baseUrl}/ics/${filename}`;
        resolve(downloadUrl);
      });
    });
  });
}
module.exports = { renderTimetableToImage, transformCourseToSubscribe };
